package com.qianfeng.smartdevice.security;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.qianfeng.smartdevice.cache.RoleCache;
import com.qianfeng.smartdevice.pojo.Menu;
import com.qianfeng.smartdevice.pojo.MyBaseUser;
import com.qianfeng.smartdevice.pojo.Role;
import com.qianfeng.smartdevice.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Jackiechan on 2022/1/14/21:44
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Component
public class MySuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    private UserRoleMapper userRoleMapper;

    private RoleCache roleCache;

    @Autowired
    public void setRoleCache(RoleCache roleCache) {
        this.roleCache = roleCache;
    }

    @Autowired
    public void setUserRoleMapper(UserRoleMapper userRoleMapper) {
        this.userRoleMapper = userRoleMapper;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //用户一定已经登录成功了
        //重新给用户设置授权
        //查询用户所有的角色,然后根据角色查询权限,最终设置给用户
        MyBaseUser principal = (MyBaseUser) authentication.getPrincipal();//这里获取到的对象就是我们在MyUserDetailService类中返回的对象
        //String username = principal.getUsername();//获取用户名
        //获取用户的id
        Long userId = principal.getUserId();
        List<Long> roleIds = userRoleMapper.selectRoleIdByUserId(userId);//根据用户的id查询角色的id
        //查询到了用户有的所有的角色
        List<Role> roleList = roleIds.parallelStream().map(rId -> roleCache.get(rId)).collect(Collectors.toList());
        //roleList中就包含了所有的角色和对应的菜单
        List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<>();//用户保存权限的集合

//        for (Role role : roleList) {
//            Set<Menu> menuList = role.getMenuList();
//            for (Menu menu : menuList) {
//                String perms = menu.getPerms();
//                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(perms);
//                grantedAuthorities.add(authority);
//            }
//        }
//

        roleList.parallelStream().map(Role::getMenuList).forEach(menus ->
                {
                    List<SimpleGrantedAuthority> simpleGrantedAuthorities = menus.parallelStream().map(Menu::getPerms).filter(perms-> StringUtils.hasText(perms)).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
                    grantedAuthorities.addAll(simpleGrantedAuthorities);//
                }
        );
        //.collect(Collectors.toSet());//当前用户所有的菜单

        //给当前登录用户刷新权限
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(principal, authentication.getCredentials(), grantedAuthorities);//用新的权限重新创建认证的对象
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);//重新给当前登录的用户刷新权限
        response.getWriter().write("success aaaaaaaaaaaa");
    }
}
